//
//  DownloadShowView.m
//  Pictorial
//
//  Created by SKY on 15/12/30.
//  Copyright © 2015年 sky. All rights reserved.
//

#import "DownloadShowView.h"
#import <UIImageView+WebCache.h>

#define DELETE_WIDTH 50

@interface DownloadShowView ()

@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UILabel *descLabel;
@property (weak, nonatomic) IBOutlet UIImageView *pictureView;

@property (nonatomic,strong) UIButton *deleteBtn;

@end

@implementation DownloadShowView

-(void)setModel:(DownloadModel *)model{
    _model = model;
    self.titleLabel.text = model.title;
    self.descLabel.text = model.desc;
    [self.titleLabel layoutIfNeeded];
    [self.descLabel layoutIfNeeded];
    [self.pictureView sd_setImageWithURL:[NSURL URLWithString:model.picture]];
}

-(void)willMoveToSuperview:(UIView *)newSuperview{
    self.frame = newSuperview.bounds;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(back)];
    [self addGestureRecognizer:tap];
    
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(showDelete)];
    [self addGestureRecognizer:longPress];
}
-(void)back{
    
    [self.deleteBtn.layer removeAllAnimations];
    
    [self removeFromSuperview];
}
-(void)showDelete{
    self.deleteBtn.hidden = NO;
    
    CAKeyframeAnimation *frameAnimation = [CAKeyframeAnimation animation];
    frameAnimation.keyPath = @"transform.rotation";
    CGFloat anlge = M_PI_2 / 90 * 20;
    frameAnimation.values = @[@(anlge),@0,@(-anlge)];
    frameAnimation.repeatCount = MAXFLOAT;
    [self.deleteBtn.layer addAnimation:frameAnimation forKey:@"shake"];
    
}
/**
 *  删除此数据
 */
-(void)deletePicture{
    
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"确定删除？" message:[NSString stringWithFormat:@"确定要删除-%@-吗？",self.model.title] preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *commitAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        
        [self back];
        [_delegate deletePictureAtIndex:self.index];
        
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertVC addAction:commitAction];
    [alertVC addAction:cancelAction];
    
    [_delegate alert:alertVC];
}
-(UIButton *)deleteBtn{
    if (_deleteBtn == nil) {
        _deleteBtn = [UIButton buttonWithLocalBgImage:@"delete.png" frame:CGRectMake(self.frame.size.width - DELETE_WIDTH - 10, 30, DELETE_WIDTH, DELETE_WIDTH) target:self sel:@selector(deletePicture)];
        [self addSubview:_deleteBtn];
        _deleteBtn.hidden = YES;
    }
    return _deleteBtn;
}

@end
